package com.zhida.jiyangcenter.modle

import android.os.Bundle
import android.util.SparseArray
import androidx.appcompat.widget.AppCompatImageView
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import chooongg.base.annotation.ContentLayout
import chooongg.base.annotation.TitleBar
import chooongg.base.loadState.LoadService
import chooongg.base.loadState.LoadUtils
import chooongg.base.loadState.callback.EmptyCallback
import chooongg.base.loadState.callback.ErrorCallback
import chooongg.base.loadState.callback.NetworkCallback
import chooongg.base.utils.gone
import chooongg.base.utils.visible
import chooongg.base.widget.recyclerView.divider.HorizontalDividerItemDecoration
import chooongg.http.APIException
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.zhida.jiyangcenter.DEFAULT_ROW
import com.zhida.jiyangcenter.R
import com.zhida.jiyangcenter.api.APIZaxiang
import com.zhida.jiyangcenter.api.BaseAPI
import com.zhida.jiyangcenter.api.ExaminationListEntity
import com.zhida.jiyangcenter.mian.BaseActivity
import com.zhida.jiyangcenter.utils.glideImage
import com.zhida.jiyangcenter.utils.request
import com.zhida.jiyangcenter.widget.imagewatcher.GlideSimpleLoader
import com.zhida.jiyangcenter.widget.imagewatcher.ImageWatcherHelper
import kotlinx.android.synthetic.main.list.*

@TitleBar(false)
@ContentLayout(R.layout.list)
class SeeEquipmentActivity : BaseActivity() {
    val adapter = Adapter()
    var page = 1
    private lateinit var loadService: LoadService<*>
    private var iwHelper: ImageWatcherHelper? = null
    override fun initConfig(savedInstanceState: Bundle?) {
        title_bar.visible()
        title_bar.title("查看报告").navigationIcon(R.drawable.iv_back_fill) {
            finish()
        }
        loadService = LoadUtils.getDefault().register(refresh_layout) {
            page = 1
            getData()
        }
        recycler_view.layoutManager = LinearLayoutManager(context)
        recycler_view.addItemDecoration(
            HorizontalDividerItemDecoration.Builder(context).colorResId(R.color.colorBack)
                .sizeResId(R.dimen.dividerBig).build()
        )
        recycler_view.adapter = adapter
        refresh_layout.setOnRefreshListener {
            page = 1
            getData()
        }
        adapter.setPreLoadNumber(3)
        adapter.setOnLoadMoreListener({
            ++page
            getData()
        }, recycler_view)
        adapter.onItemDragPhotoListener= { position, view, layoutPosition ->
            val mappingViews = SparseArray<AppCompatImageView>()
            mappingViews.put(position, view)
            val longPictureList = ArrayList<String>()
            adapter.data[layoutPosition].picture?.forEach {
                longPictureList.add(it)
            }
            iwHelper?.show(view, mappingViews, iwHelper?.convert(longPictureList))
        }
        getData()
        iwHelper =
            ImageWatcherHelper.with(activity, GlideSimpleLoader()) // 一般来讲， ImageWatcher 需要占据全屏的位置
                .setErrorImageRes(R.drawable.error_picture)
    }

    private fun getData() {
        lifecycleScope.request({ APIZaxiang.service().examinationList(page) },
            object : BaseAPI<List<ExaminationListEntity>>() {
                override fun onSuccess(t: List<ExaminationListEntity>?, state: Int, msg: String) {
                    if (t != null && !t.isNullOrEmpty()) {
                        if (page <= 1) {
                            adapter.setNewData(t)
                            loadService.showSuccess()
                            refresh_layout.finishRefresh()
                            if (t.size < DEFAULT_ROW) {
                                adapter.loadMoreEnd(true)
                            }
                        } else {
                            adapter.addData(t)
                            if (t.size < DEFAULT_ROW) {
                                adapter.loadMoreEnd(true)
                            } else adapter.loadMoreComplete()
                        }
                    } else onError(APIException(APIException.Type.EMPTY))
                }

                override fun onError(e: APIException) {
                    if (page <= 1) when (e.type) {
                        APIException.Type.EMPTY -> loadService.showCallback(
                            EmptyCallback::class,
                            "暂无商品"
                        )
                        APIException.Type.ERROR_NETWORK -> loadService.showCallback(NetworkCallback::class)
//                        APIException.Type.NOT_LOGIN -> loadService.showCallback(NotLoginCallback::class)
                        else -> loadService.showCallback(ErrorCallback::class, e.eMessage)
                    } else when (e.type) {
                        APIException.Type.EMPTY -> {
                            adapter.loadMoreFail()
                        }
                        else -> adapter.loadMoreFail()
                    }
                }

            })
    }

    class Adapter :
        BaseQuickAdapter<ExaminationListEntity, BaseViewHolder>(R.layout.item_see_equipmet) {
        var onItemDragPhotoListener: ((position: Int, view: AppCompatImageView, layoutPosition: Int) -> Unit)? = null
        override fun convert(helper: BaseViewHolder, item: ExaminationListEntity?) {
            helper.setText(R.id.tv_content, item?.description)
            val recyclerView = helper.getView<RecyclerView>(R.id.recycler_picture_view)
            if (recyclerView.layoutManager == null) {
                recyclerView.layoutManager = object : GridLayoutManager(mContext, 3) {
                    override fun canScrollVertically() = false
                }
            }
            if (item?.picture.isNullOrEmpty()) {
                recyclerView.gone()
                recyclerView.adapter = null
            } else {
                recyclerView.visible()
                val adapter = PictureAdapter()
                adapter.bindToRecyclerView(recyclerView)
                adapter.setNewData(item?.picture)
                adapter.setOnItemClickListener { _, view, position ->
                    onItemDragPhotoListener?.invoke(position, view.findViewById(R.id.iv_image), helper.layoutPosition - headerLayoutCount)
                }
            }
        }

        private inner class PictureAdapter :
            BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_seller_discuss_picture) {
            override fun convert(helper: BaseViewHolder, item: String?) {
                val imageView = helper.getView<AppCompatImageView>(R.id.iv_image)
                glideImage(imageView, item ?: "", R.color.colorBack)
            }
        }
    }
}